from django.shortcuts import render
from django.http import HttpResponse
import os,time
from . models import *

# Create your views here.
def index(request):
    
    # return HttpResponse('网站后台首页')
    # 加载后台模板
    return render(request,'myadmin/index.html')

# -------------后台登录-------------------
def login(request):
    
    # 加载模板,显示登录页面
    return render(request,'myadmin/login/login.html')
# 处理登录
def dologin(request):
    
    # 首先判断验证码填写是否正确
    if request.session['verifycode'] != request.POST['code'].upper():
        return HttpResponse('<script>alert("验证码不正确");location.href="/admin/login";</script>')

    try:
        # 判断用户名是否存在,
        ob = Users.objects.get(username = request.POST['username'])
        # 以及是否具有权限,(管理员)
        if ob.state == 0:
            # 如果存在,判断密码是否正确
            from django.contrib.auth.hashers import make_password, check_password
            if check_password(request.POST['password'],ob.password):
                # 如果密码正确,把用户信息写入session,来标记用户的登录行为
                request.session['Vuser'] = {"uid":ob.id,"username":ob.username,"pic":ob.pic}
                # 跳转到首页
                return HttpResponse('<script>alert("登录成功");location.href="/admin";</script>')
            else:
                return HttpResponse('<script>alert("用户名或密码错误");location.href="/admin/login";</script>')
        else:
            return HttpResponse('<script>alert("用户不存在");location.href="/admin/login";</script>')
    except:
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/admin/login";</script>')




    # 加载模板,显示登录页面
    return HttpResponse('处理登录')

# 退出登录
def loginout(request):
    # 清除登录信息
    request.session['Vuser'] = ''

    return HttpResponse('<script>alert("退出成功");location.href="/admin/login";</script>')




# 用户列表
def userindex(request,pIndex = 1):

    # 查询所有的用户信息
    ob = Users.objects.filter()   

    # 判断是否有搜索条件
    if request.GET.get('class') == 'username':
        ob = Users.objects.filter(username__contains=request.GET.get('keywords'))
    # 判断是否有搜索条件
    if request.GET.get('class') == 'phone':
        ob = Users.objects.filter(phone__contains=request.GET.get('keywords'))
    # 判断是否有搜索条件
    if request.GET.get('class') == 'sex':
        if request.GET.get('keywords') == '男':
            ob = Users.objects.filter(sex=1)
        else:
            ob = Users.objects.filter(sex=0)
    # 准备where条件 搜索条件
    where = {'class':request.GET.get('class',''),'keywords':request.GET.get('keywords','')}
    wherestr = ''
    for k,v in where.items():
        wherestr += k+'='+v+'&'

    from django.core.paginator import Paginator
    pIndex = int(pIndex)
    # 实例化分页类
    paginator = Paginator(ob,100)
    # 获取分页数据对象
    list2 = paginator.page(pIndex)
    # 分配数据
    context = {'ulist':list2,'where':wherestr}
    # 解析模板
    return render(request,'myadmin/user/index.html',context)

# 会员添加
def useradd(request):
    
    # 加载表单
    return render(request,'myadmin/user/add.html')

#会员数据添加
def userinsert(request):
    from django.contrib.auth.hashers import make_password, check_password

    try:
        # 数据的添加
        ob = Users()
        ob.username = request.POST['username']
        # 密码
        ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        ob.sex = request.POST['sex']
        ob.address = request.POST['address']
        ob.code = request.POST['code']
        ob.phone = request.POST['phone']
        ob.state = request.POST['state']
        ob.pic = myadmin_upload(request)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="/admin/user/index";</script>')
    except:
        return HttpResponse('<script>alert("添加失败,请联系管理员");location.href="/admin/user/add";</script>')

# 会员删除
def userdel(request,uid):
    try:
        # 删除
        ob = Users.objects.get(id = uid)
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="/admin/user/index";</script>')
    except:
        return HttpResponse('<script>alert("删除失败,请联系管理员");location.href="/admin/user/index";</script>')


# 会员编辑
def useredit(request,uid):
    # 根据用户id查询当前用户信息
    ob = Users.objects.get(id=uid)
    # 分配数据
    context = {'uinfo':ob}
    # 加载模板
    return render(request,'myadmin/user/edit.html',context) 

# 执行会员修改
def userupdate(request):
    try:
        # 根据用户id获取用户对象
        ob = Users.objects.get(id=request.POST['uid'])

        ob.phone = request.POST['phone']
        ob.sex = request.POST['sex']
        ob.address = request.POST['address']
        ob.code = request.POST['code']
        ob.state = request.POST['state']
        # 判断是否有头像上传
        myfile = request.FILES.get("pic",None)
        if myfile:
            # 判断是否为默认头像
            if ob.pic != 'user.jpg':
                # 把原来的用户头像删除
                os.remove('./static/myadmin/pics/'+ob.pic)
            # 上传则获取新的头像
            ob.pic = myadmin_upload(request)

        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="/admin/user/index";</script>')
    except:
        return HttpResponse('<script>alert("修改失败,请联系管理员");location.href="/admin/user/edit/'+ob.id+'";</script>')


# 执行文件上传操作
def myadmin_upload(request): 
    #执行图片的上传
    myfile = request.FILES.get("pic",None)
    if not myfile:
        return 'user.jpg'
    filename = str(time.time())+"."+myfile.name.split('.').pop()
    destination = open("./static/myadmin/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()
    return filename

# 绘制验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('static/myfont.TTF', 23)
    # font = ImageFont.load_default().font
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, -2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')